<?php
namespace frontend\controllers;

use Yii;
use common\models\User;
use yii\data\ActiveDataProvider;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\Order;
use common\models\Mclass;
use yii\data\Pagination;
use common\models\Record;
use common\models\Address;
use common\models\Cart;
use common\models\District;
use common\models\Goods;
use common\models\Collect;
use frontend\controllers\base\BaseController;
use frontend\models\ResetPasswordForm;
use yii\filters\AccessControl;
use common\models\Oinfo;
use frontend\models\SafeForm;
/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends BaseController
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => [
                            'login',
                            'error'
                        ],
                        'allow' => true
                    ],
                    [
                        'allow' => true,
                        'roles' => [
                            '@'
                        ]
                    ]
                ]
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => [
                        'POST'
                    ],
                    'delcart'=>['POST'],
                    'del-collect'=>['POST']
                ]
            ]
        ];
    }

    /**
     * Lists all User models.
     * 
     * @return mixed
     */
    public function actionIndex()
    {
        $this->layout='user.php';
        $dataProvider = new ActiveDataProvider([
            'query' => User::find()
        ]);
        $uid=Yii::$app->user->id;
        $order=Order::find()->with('oinfo')->where('uid='.$uid.' and status>0')->asArray()->limit(3)->all();
        $record=Record::find()->with('goods')->where(['uid'=>$uid])->limit(9)->asArray()->all();
        $collect=Collect::find()->with('goods')->where(['uid'=>$uid])->limit(5)->asArray()->all();
        $this->columnData();
        $this->showCart();
        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'record'=>$record,
            'collect'=>$collect,
            'order'=>$order
        ]);
    }
    /**
     * Displays a single User model.
     * 
     * @param integer $id            
     * @return mixed
     */
    public function actionView()
    {
        $this->layout = 'user.php';
        $id = Yii::$app->user->id;
        if (! $id) {
            return $this->redirect([
                '/site/index'
            ]);
        }
        return $this->render('view', []

        );
    }
    //收货地址
    public function actionAddress(){
        $this->layout = 'user.php';
        $model=new Address();
        $data=$model->find()->where('uid='.Yii::$app->user->id)->asArray()->all();
        if(!empty($data)){
            $district=$this->area($data);
        }
        if($model->load(Yii::$app->request->post()) && $model->save()){
            return $this->redirect('address.html');
        }
        $this->columnData();
        $this->showCart();
        return $this->render('address',[
            'data'=>$data,
            'district'=>$district
        ]);
    }
    public function actionCollect(){
        $this->layout = 'user.php';
        $model=Collect::find()->with('goods')->where('uid='.Yii::$app->user->id);
        $pages=new Pagination(['totalCount'=>$model->count(),'pageSize'=>16]);
        $data=$model->offset($pages->offset)->limit($pages->limit)->asArray()->all();
        $this->columnData();
        $this->showCart();
        return $this->render('collect',
            ['data'=>$data,'pages'=>$pages]
            );
    }
    public function actionDelCollect($id){
        $flag=Collect::deleteAll(['id'=>$id,'uid'=>Yii::$app->user->id]);
        echo json_encode($flag);exit;
    }
    /**
     * 购物车
     */
    public function actionCart(){
        $this->columnData();
        $this->showCart();
        $hot=Goods::find()->where('hot=1')->select('id,name,price,logo,look')->asArray()->all();//推荐宝贝
        $cart=Cart::find()->with('goods')->where('uid='.Yii::$app->user->id)->orderBy('id desc')->asArray()->all();
        return $this->render('cart',[
            'cart'=>$cart,
            'hot'=>$hot
        ]);
    }
    /**
     * 删除单个购物车商品
     * @param int $id
     */
    public function actionDelcart($id){
        $data=Cart::deleteAll(
            ['id'=>(int)$id,'uid'=>Yii::$app->user->id]
        );
        echo json_encode($data);exit;
    }
    /**
     * 删除多个购物车商品
     */
    public function actionDelcartall(){
        $post=Yii::$app->request->post();
        if(isset($post['ids']) && !empty($_POST['ids'])){
           $data=Cart::deleteAll('id in ('.implode(',',$_POST['ids']).') and uid='.Yii::$app->user->id);   
        }
        echo json_encode($data);
    }
    /**
     * 修改购物车数量
     */
    public function actionUpcart(){
        $post=Yii::$app->request->post();
        if(isset($post['id']) && isset($post['num'])){
            Cart::updateAll(['num'=>max($post['num'],1)],'id='.$post['id'].' and uid='.Yii::$app->user->id);
        }
    }
    /**
     * 订单管理
     */
    public function actionOrder(){
        $this->layout = 'user.php';
        $this->columnData();
        $this->showCart();
        $where='';
        $uid=Yii::$app->user->id;
        $status=Order::find()->select('status,count(id) num')->where('status in (0,1,2) and uid='.Yii::$app->user->id)->groupBy('status')->asArray()->all();
        if(!empty($status)) $status=array_column($status, 'num','id');
        $order=Order::find()->with('oinfo')->where('uid='.$uid.$where);
        $get=Yii::$app->request->get();
        if(isset($_GET['search'])){//订单搜索
            if(substr($get['search'],0,18)>100000000000000000){
                $where=' and omun='.$get['search'];
            }else{
                $where=" and id in (select oid from oinfo where oid in (select id from `order` where uid={$uid}) and name like '%{$get['search']}%')";
            }
        }
        if(isset($get['name'])) $where=' and status='.(int)$get['name'];
        $pages=new Pagination(['totalCount'=>$order->count(),'pageSize'=>10]);//分页
        $order=$order->offset($pages->offset)->limit($pages->limit)->asArray()->all();
        return $this->render('order',[
            'order'=>$order,'status'=>$status,'pages'=>$pages
        ]);
    }
    /**
     * 完成订单
     */
    public function actionFulfil($id){
        $model=Order::findOne(['id'=>$id,'status'=>2,'uid'=>Yii::$app->user->id]);
        if($model){
            $model->status=3;
            if($model->save(false,['status'])){
                echo json_encode(true);exit;
            }
        }
        echo json_encode(false);exit;
    }
    /**
     * 订单详情
     * @param unknown $id
     */
    public function actionOdetail($id){
        $this->layout = 'user.php';
        $this->columnData();
        $this->showCart();
        $order=Order::find()->with('oinfo')->with('bom')->where('omun='.$id.' and uid='.Yii::$app->user->id)->asArray()->one();
        if($order['status']>1){
            $kd=$this->getOrderTracesByJson($order['bom']['name'],$order['waybill']);
            $kd=json_decode($kd,true);
        }
        return $this->render('odetail',['order'=>$order,'kd'=>$kd]);
    }
    /**
     * 添加修改收货地址
     * @param unknown $id
     */
    public function actionUpaddress(){
        $id=(int)$_GET['id'];
        if($id){//判断是否为修改地址
            $model=Address::findOne(['id'=>$id,'uid'=>Yii::$app->user->id]);
        }else{
            $model=new Address();
        }
        $post=Yii::$app->request->post();
        if($model->load($post)){
            if($model->status==1){
                Address::updateAll(['status'=>0],['uid'=>Yii::$app->user->id]);
            }
            if($model->save()){
                echo json_encode([$model->id]);exit;
            }else{
                echo json_encode($model->getErrors());exit;
            }
        }else{
            echo json_encode($model->getErrors());exit;
        }
        
    }
    public function actionDelete($id){
        $data=Address::deleteAll(['id'=>$id,'uid'=>Yii::$app->user->id]);
        echo json_encode($data);exit;
    }
    public function actionRecord(){
        $this->layout = 'user.php';
        $this->columnData();
        $this->showCart();
        return $this->render('record');
    }
    public function actionPassword(){
        $this->layout = 'user.php';
        $this->columnData();
        $this->showCart();
        return $this->render('password');
    }
    /*
    public function actionInfo(){
        $this->layout = 'user.php';
        $model=new ResetPasswordForm();
        $post=Yii::$app->request->post();
        if($post){
            if($model->load($post) && $model->validate()){
                $flag=0;//验证码不正确
                $code=Yii::$app->session->get('code');
                if(!empty($code[2])){
                    if($code[2]['tel']==Yii::$app->user->identity->tel && $code[2]['code']==$model->code){
                        if($model->resetPassword()){
                            $flag=1;//修改成功
                        }else{
                            $flag=2;//修改失败
                        }
                    }
                }
                echo json_encode([$flag]);
            }else{
                echo json_encode($model->getErrors());
            }
            exit;
        }
        $this->columnData();
        $this->showCart();
        return $this->render('info');
    }*/
    /**
     * 安全中心
     */
    public function actionSafe(){
        $this->layout = 'user.php';
        $flag=false;
        $get=Yii::$app->request->get();
        if(isset($get['flag'])){
            $post=Yii::$app->request->post();
            $code=Yii::$app->session->get('code');
            $model=new SafeForm();
            if(isset($post['SafeForm']['password'])){
                $flag=1;
                $model->setScenario('uppwd');
            }elseif(isset($post['SafeForm']['tel'])){
                $flag=1;
                $model->setScenario('uptel');
            }else{
                $model->setScenario('code');
            }
            if($model->load($post) && $model->validate()){
                $k=2;
                if($get['flag']==2) $k=4;
                if(isset($code[$k]) && $code[$k]['code']==$model->code){
                    $flag=1;
                    if($model->password!=null && $get['flag']==1){
                        if($model->resetPassword()){
                            $flag=2;
                        }
                    }elseif($get['flag']==2){
                        if(isset($code[5]) && $code[5]['code']==$model->upcode && $code[5]['tel']==$model->tel){
                             if($model->resetTel()){
                                 $flag=2;
                             }
                        }else{
                            $model->addError('upcode','验证码错误');
                        }
                    }
                }else{
                    $flag=false;
                    $model->addError('code','验证码错误');
                }
            }
        }
        $this->columnData();
        $this->showCart();
        return $this->render('safe',['flag'=>$flag,'model'=>$model]);
    }
    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * 
     * @param integer $id            
     * @return mixed
     */
    public function actionUpdate()
    {
        $this->layout = 'user.php';
        $post = Yii::$app->request->post();
        if ($post) {
            if (md5($post['User']['password']) == Yii::$app->user->identity->password) {
                Yii::$app->user->identity->password = md5($post['User']['rpassword']);
                Yii::$app->user->identity->save();
                Yii::$app->user->logout();
                
                return $this->goHome();
            } else {
                Yii::$app->getSession()->setFlash('error', '原密码不正确');
            }
        }
        return $this->render('update');
    }

    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * 
     * @param integer $id            
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    /**
     * 返回省市区数据
     * @param unknown $data
     * @return \yii\db\ActiveRecord[]
     */
    public function area($data){
        $district=[];
        $province=array_column($data,'province');
        $city=array_column($data, 'city');
        $community=array_column($data, 'community');
        $ids=array_unique(array_merge($province,$city,$community));
        $district=District::find()->where('id in ('.implode(',', $ids).')')->asArray()->all();
        if(!empty($district)) $district=array_column($district,'name','id');
        return $district;
    }
}
